//
//  UPCustomTabBarItem.m
//  Uang Pasti
//
//  Created by 李永彬 on 2025/8/17.
//

#import "UPCustomTabBarItem.h"
#import <Masonry/Masonry.h>

@interface UPCustomTabBarItem ()

@property (nonatomic, strong) UIImageView *iconImageView;
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UIStackView *stackView;

@end

@implementation UPCustomTabBarItem

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self setupView];
    }
    return self;
}

- (instancetype)initWithCoder:(NSCoder *)coder {
    self = [super initWithCoder:coder];
    if (self) {
        [self setupView];
    }
    return self;
}

- (void)setupView {
    _normalColor = [UIColor grayColor];
    _selectedColor = [UIColor systemBlueColor];
    
    // 创建子视图
    _iconImageView = [[UIImageView alloc] init];
    _iconImageView.contentMode = UIViewContentModeScaleAspectFit;
    
    _titleLabel = [[UILabel alloc] init];
    _titleLabel.font = [UIFont systemFontOfSize:15 weight:UIFontWeightBold];
    _titleLabel.textColor = [UIColor colorWithHexString:@"#FFFFFF"];
    _titleLabel.textAlignment = NSTextAlignmentCenter;
    
    _stackView = [[UIStackView alloc] init];
    _stackView.axis = UILayoutConstraintAxisVertical;
    _stackView.alignment = UIStackViewAlignmentCenter;
    _stackView.distribution = UIStackViewDistributionFill;
    _stackView.spacing = 4;
    _stackView.userInteractionEnabled = NO;
    
    // 添加子视图
    [self addSubview:_stackView];
//    [_stackView addArrangedSubview:_iconImageView];
     [_stackView addArrangedSubview:_titleLabel]; // 如果需要标题可以取消注释
    
    // 设置约束
    [_stackView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.centerY.equalTo(self);
    }];
    
    [_iconImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.width.equalTo(@24);
    }];
}

- (void)setSelected:(BOOL)selected {
    [super setSelected:selected];
    [self updateAppearance];
}

- (void)updateAppearance {
    if (self.isSelected) {
        _titleLabel.textColor = _selectedColor;
        _iconImageView.image = _selectedIcon ?: _icon;
        _iconImageView.tintColor = _selectedColor;
    } else {
        _titleLabel.textColor = _normalColor;
        _iconImageView.image = _icon;
        _iconImageView.tintColor = _normalColor;
    }
}

- (void)setTitle:(NSString *)title {
    _title = [title copy];
    _titleLabel.text = title;
}

- (void)setIcon:(UIImage *)icon {
    _icon = icon;
    [self updateAppearance];
}

- (void)setNormalColor:(UIColor *)normalColor {
    _normalColor = normalColor;
    [self updateAppearance];
}

- (void)setSelectedColor:(UIColor *)selectedColor {
    _selectedColor = selectedColor;
    [self updateAppearance];
}

@end
